package org.ziegler.netty.cp8;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

import java.net.InetSocketAddress;

public class DatagramServer {
    public static void main(String[] args) {
        DatagramServer datagramTest = new DatagramServer();
        datagramTest.start(8887);
    }
    void start(int port) {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup())
                .option(ChannelOption.SO_BROADCAST, true)
                .channel(NioDatagramChannel.class)
                .localAddress(new InetSocketAddress(port))
                .handler(new SimpleChannelInboundHandler<ByteBuf>() {
                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        super.channelActive(ctx);
                        System.out.println("DatagramTest.channelActive");
                    }

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
                        System.out.println("DatagramTest.channelRead0" + msg);
                    }
                });

        ChannelFuture future = bootstrap.bind();
        future.addListener(future1 -> {
            if (future1.isSuccess()) {
                System.out.println("channel bound");
            } else {
                System.err.println("Bind attempt fail");
                future1.cause().printStackTrace();
            }
        });
    }
}
